/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef GAME_GAMESYSTEM_H_
#define GAME_GAMESYSTEM_H_

#include <ctime>
#include <boost/unordered_map.hpp>
#include "Shared/DB/DB.h"
#include "Shared/Base/Event.h"
#include "Shared/Base/Mutex.h"
#include "Shared/Net/TcpServer.h"
#include "Shared/Util/SubSystem.h"
#include "Game/Server/GameSocketHandler.h"
#include "Game/World/World.h"
#include "Game/World/WorldThread.h"


class GameSystem: public Shared::Util::SubSystem
{
public:
    GameSystem(void);
    virtual ~GameSystem(void);

    virtual bool initialize(void);
    virtual void run(void);
    virtual void uninitialize(void);
    virtual void onSignal(int signal);

    void shutdown(void);

    Shared::Database& loginDB(void) { return _loginDB; }
    Shared::Database& charaDB(void) { return _charaDB; }
    Shared::Database& worldDB(void) { return _worldDB; }
    std::uint32_t realmID(void) const { return _realmID; }

    bool addUnauthedSocket(int id, GameSocketHandler *sock);
    bool moveSocketAuthed(int id);
private:

    void updateUnauthedSocket(void);
    void updateAuthedSockets(void);
    void closeSockets(void);


    Shared::Database _loginDB;
    Shared::Database _charaDB;
    Shared::Database _worldDB;
    int _dbPingTime;
    Shared::Net::TcpServer _NetServer;

    World _world;
    WorldThread _worldThread;

    std::uint32_t _realmID;

    Shared::Event _stopEvent;
    volatile bool _running;

    ///////////////////////////////////////////////////////////////////////////
    typedef boost::unordered_map<int, GameSocketHandler*> UnauthedSocketMap;
    typedef boost::unordered_map<std::uint32_t, GameSocketHandler*> AuthedSocketMap;

    time_t _maxAuthTime;
    UnauthedSocketMap _unAuthedSockets;
    AuthedSocketMap _authedSockets;
    AuthedSocketMap _closingSockets;
    Shared::Mutex _unAuthedSocketsLock;
    Shared::Mutex _authedSocketsLock;
};

#endif /* GAME_GAMESYSTEM_H_ */